package com.hhu.wangzb.shiro.config;
import com.hhu.wangzb.shiro.filter.JwtFilter;
import com.hhu.wangzb.shiro.realm.AccountRealm;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;

/**
 * Shiro的基本配置类
 */
@Configuration
public class ShiroConfig {

    /**
     * 注册ShiroFilter过滤器
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        // 为过滤器添加处理认证和授权的安全管理器
        shiroFilter.setSecurityManager(securityManager());

        // 指定某个请求要使用某个过滤器处理
        HashMap<String, String> filterChainDefinitionMap = new HashMap<>();

        // 自定义过滤器
        HashMap<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());
        shiroFilter.setFilters(filterMap);

        // 排除资源访问受限
        // 静态资源
        filterChainDefinitionMap.put("/access/**", "anon");

        // swagger
        filterChainDefinitionMap.put("/test/**", "anon");

        // 登陆请求排除
        filterChainDefinitionMap.put("/authenticate", "anon");

        // swagger接口文档
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");

        // 全部资源访问需要jwt授权后访问
        filterChainDefinitionMap.put("/**", "jwt");

        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
        // 设置登陆页面url 登陆页面默认不需要认证授权
        // 未认证时访问资源，则会转发到该请求路径
        shiroFilter.setLoginUrl("/forbidden");
        shiroFilter.setUnauthorizedUrl("/forbidden");

        return shiroFilter;
    }

    /**
     * 注册web应用中默认的安全管理器 DefaultWebSecurityManager
     */
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm());


        return securityManager;
    }

    /**
     * 注册自定义Realm
     */
    @Bean
    public AccountRealm accountRealm() {

        return new AccountRealm();
    }

}
